package com.ycsj.goldmedalnewconcept.activity;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;

/**
 * 创建日期：2017/11/6 14:56 描述:模板预览界面 作者:张伟
 */

public class SkinListActivity extends Activity implements View.OnClickListener {

	// 返回
	private LinearLayout llBack;

	// 保存
	private TextView tvSave;

	private ImageView lvCenterTop;

	// 加载框
	private LinearLayout llLoading;

	protected static final int THEME_ID = 0;
	
	// 三张图片的ImageView
	private ImageView lvTop, lvCenter, lvBottom;
	
	private String top;
	
	private String center;
	
	private String bottom;

	private FrameLayout fl;

	private RelativeLayout rlCenter;

	// 打开系统相册相关操作
	private final String IMAGE_TYPE = "image/*";
	public static final int IMAGE_REQUEST_CODE = 0x102;

	// 拍照的请求码
	public static final int CAMERA_REQUEST_CODE = 0X108;

	// 图片裁剪的请求码
	private static final int PHONE_CODE__CUT = 0x120;

	// 用于记录裁剪图片后的保存路径
	private String cropPath;

	private String imagePath;

	private String themeId;

	// 弹框选择相关
	private View view;
	
	private TextView tvCamera;
	
	private TextView tvPic;
	
	private TextView tvCancel;
	
	private PopupWindow popupWindow;

	protected static Uri tempUri;

	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_skin_list);

		// 设置状态栏颜色
		setBar();

		// 初始化控件
		initViews();

		// 获取上中下三张图片信息
		initIntent();

		// 设置监听
		initListener();

		// 设置图片数据
		setData();
	}

	/**
	 * 初始化控件的方法
	 */
	private void initViews() {
		// 获取屏幕宽度
		WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		int screenHeight = wm.getDefaultDisplay().getHeight();

		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
				ViewGroup.LayoutParams.MATCH_PARENT, screenHeight / 3);

		llBack = (LinearLayout) findViewById(R.id.ll_back);
		tvSave = (TextView) findViewById(R.id.tv_save);
		lvTop = (ImageView) findViewById(R.id.lv_top);
		lvCenter = (ImageView) findViewById(R.id.lv_center);
		lvBottom = (ImageView) findViewById(R.id.lv_bottom);
		fl = (FrameLayout) findViewById(R.id.fl_center);
		lvCenterTop = (ImageView) findViewById(R.id.lv_center_top);
		rlCenter = (RelativeLayout) findViewById(R.id.rl_center);
		lvTop.setLayoutParams(lp);
		fl.setLayoutParams(lp);
		lvBottom.setLayoutParams(lp);

	}

	/**
	 * 获取页面传递过来的数据
	 */
	private void initIntent() {
		Intent intent = getIntent();
		top = intent.getStringExtra("top");
		center = intent.getStringExtra("center");
		Log.i("test", "中间图片的值是:" + center);
		bottom = intent.getStringExtra("bottom");
		themeId = intent.getStringExtra("themeId");
	}

	/**
	 * 设置三张图片数据
	 */
	private void setData() {
		if (llLoading != null) {
			llLoading.setVisibility(llLoading.GONE);
		}
		Picasso.with(this).load(top).error(R.drawable.defaultimage).into(lvTop);
		Picasso.with(this).load(center).error(R.drawable.defaultimage)
				.into(lvCenter);
		Picasso.with(this).load(bottom).error(R.drawable.down).into(lvBottom);
	}

	/**
	 * 设置监听的方法
	 */
	private void initListener() {
		llBack.setOnClickListener(this);
		tvSave.setOnClickListener(this);
		rlCenter.setOnClickListener(this);
	}

	/**
	 * 设置沉浸状态栏的方法,需要在setContentView()之后调用
	 */
	@SuppressLint("NewApi")
	private void setBar() {
		// 兼容5.0+，状态栏设置透明
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
			Window window = getWindow();
			window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			window.getDecorView().setSystemUiVisibility(
					View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
							| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
			window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
			window.setStatusBarColor(Color.TRANSPARENT);
		} else
		// 为了沉浸式状态栏 4.4以上才有
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			getWindow().addFlags(
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
		}
	}

	/**
	 * 跳转到系统相册的方法
	 */
	public void openAlbum() {

		// 打开系统相册的方法:
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
				"image/*");
		startActivityForResult(intent, IMAGE_REQUEST_CODE);
	}

	/**
	 * 页面控件点击事件
	 *
	 * @param view
	 */
	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.ll_back:
			// 返回
			finish();
			break;
		case R.id.tv_save:
			// 保存
			Intent mIntent = new Intent(this, CreatRedPackageActivity.class);
			SPUtil.putString(this, "imagePath", imagePath);
			SPUtil.putString(this, "themeId", themeId);
			// 设置结果，并进行传送
			startActivity(mIntent);
			Toast.makeText(this, "模板保存成功", 0).show();
			finish();
			break;
		case R.id.rl_center:
			// 点击中间图片弹框操作
			showPopUpWindow();
			break;
		case R.id.tv_camera:
			// 选择拍照
			doCameraAction();
			if (popupWindow != null && popupWindow.isShowing()) {
				popupWindow.dismiss();
				view = null;
			}
			break;
		case R.id.tv_pic:
			// 选择相册
			try {
				openAlbum();
				if (popupWindow != null && popupWindow.isShowing()) {
					popupWindow.dismiss();
					view = null;
				}
			} catch (Exception e) {
				Log.e("error", "error" + e.toString());
			}
			break;
		case R.id.tv_cancel:
			if (popupWindow != null && popupWindow.isShowing()) {
				popupWindow.dismiss();
				view = null;
			}
			break;
		}
	}

	/**
	 * 打开系统拍照的方法
	 */
	private void doCameraAction() {
		Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		tempUri = Uri.fromFile(new File(Environment
				.getExternalStorageDirectory(), "teakpic.jpg"));
		openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
		startActivityForResult(openCameraIntent, CAMERA_REQUEST_CODE);
	}

	/**
	 * 弹出相册或者是拍照的对话框
	 */
	private void showPopUpWindow() {
		view = View.inflate(this, R.layout.pop_choose_pic, null);
		tvCamera = (TextView) view.findViewById(R.id.tv_camera);
		tvPic = (TextView) view.findViewById(R.id.tv_pic);
		tvCancel = (TextView) view.findViewById(R.id.tv_cancel);
		tvCamera.setOnClickListener(this);
		tvPic.setOnClickListener(this);
		tvCancel.setOnClickListener(this);
		popupWindow = new PopupWindow(view,
				WindowManager.LayoutParams.MATCH_PARENT,
				WindowManager.LayoutParams.WRAP_CONTENT);
		popupWindow.setFocusable(true);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		backgroundAlpha(this, 0.3f);
		popupWindow.setAnimationStyle(R.style.pop_common_style);
		popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
			@Override
			public void onDismiss() {
				backgroundAlpha(SkinListActivity.this, 1.0f);
				if (popupWindow != null && popupWindow.isShowing()) {
					popupWindow = null;
					view = null;
				}
			}
		});
		popupWindow.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM,
				0, 0);
	}

	/**
	 * 改变屏幕透明度 方法
	 *
	 * @param bgAlpha
	 */
	public void backgroundAlpha(Activity activity, float bgAlpha) {
		WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
		lp.alpha = bgAlpha;
		activity.getWindow().setAttributes(lp);
	}

	/**
	 * 选择系统相册图片后的回调方法
	 *
	 * @param requestCode
	 * @param resultCode
	 * @param data
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.i("test", "data的值是:" + data);
		// 获取到调用系统相册后选择的图片信息,然后调用裁剪库功能
		if (data != null && requestCode == IMAGE_REQUEST_CODE) {
			// 调用原生系统裁剪功能
			cropImage(data.getData());
		} else if (resultCode == RESULT_OK
				&& requestCode == CAMERA_REQUEST_CODE) {
			// 调用原生系统裁剪功能
			cropImage(tempUri);
		}

		// 获取到裁剪后的图片信息
		if (requestCode == PHONE_CODE__CUT) {
			if (data != null) {

				// 获取调用原生裁剪功能后的图片地址,只能获取到Bitmap对象
				Bitmap bitmap = data.getExtras().getParcelable("data");

				SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
						"yyyyMMddHHmmss");
				Date date = new Date();
				String imageName = simpleDateFormat.format(date);
				imagePath = imageName;
				// 获取文件的地址用于生成文件
				try {
					saveFile(bitmap, imagePath + ".png");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				cropPath = data.getAction();
				lvCenterTop.setImageBitmap(bitmap);
			}
		}
	}

	/**
	 * 调用系统原生的裁剪方法
	 *
	 * @param uri
	 */
	public void cropImage(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 320);
		intent.putExtra("aspectY", 240);
		intent.putExtra("outputX", 320);
		intent.putExtra("outputY", 240);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, PHONE_CODE__CUT);
	}

	/**
	 * 保存文件
	 * 
	 * @param bm
	 * @param fileName
	 * @throws IOException
	 */
	public void saveFile(Bitmap bm, String fileName) throws IOException {
		String path = getSDPath() + "/goldupload/";
		File dirFile = new File(path);
		if (!dirFile.exists()) {
			dirFile.mkdir();
		}

		File myCaptureFile = new File(path + fileName);
		BufferedOutputStream bos = new BufferedOutputStream(
				new FileOutputStream(myCaptureFile));
		bm.compress(Bitmap.CompressFormat.PNG, 100, bos);
		bos.flush();
		bos.close();
	}

	public String getSDPath() {
		File sdDir = null;
		boolean sdCardExist = Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
		if (sdCardExist) {
			sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
		} else {
			sdDir = getFilesDir();
		}
		return sdDir.toString();
	}
}
